package com.sywb.chuangyebao.lifecycle;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;

import com.sywb.chuangyebao.bean.ActivityBean;

import org.bining.footstone.log.Logger;
import org.bining.footstone.mvp.IActivity;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.ToastUtils;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public class ActivityLifecycleCallbackImpl implements Application.ActivityLifecycleCallbacks {

    private int foregroundActivityCount = 0;// 处于前台的Activity总数量
    private boolean isChangingConfigActivity = false;// 是否在进行横竖屏切换
    private boolean willSwitchToForeground = false;// 将判断是否进入前台的时机延后到onResume来做
    private boolean isForegroundNow = false;// 当前是否处于前台

    private String lastPausedActivityName;
    private int lastPausedActivityHashCode;
    private long lastPausedTime;
    private long appUseReduceTime = 0;

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        Logger.e(activity + " onActivityCreated");

        // // 这里全局给Activity设置toolbar和title,你想象力有多丰富,这里就有多强大,以前放到BaseActivity的操作都可以放到这里
        // if (activity.findViewById(R.categoryId.toolbar) != null) {
        // if (activity instanceof AppCompatActivity) {
        // ((AppCompatActivity) activity).setSupportActionBar((Toolbar) activity.findViewById(R.categoryId.toolbar));
        // ((AppCompatActivity) activity).getSupportActionBar().setDisplayShowTitleEnabled(false);
        // } else {
        // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // activity.setActionBar((android.widget.Toolbar) activity.findViewById(R.categoryId.toolbar));
        // activity.getActionBar().setDisplayShowTitleEnabled(false);
        // }
        // }
        // }
        // if (activity.findViewById(R.categoryId.toolbar_title) != null) {
        // ((TextView) activity.findViewById(R.categoryId.toolbar_title)).setText(activity.getTitle());
        // }
        // if (activity.findViewById(R.categoryId.toolbar_back) != null) {
        // activity.findViewById(R.categoryId.toolbar_back).setOnClickListener(v -> {
        // activity.onBackPressed();
        // });
        // }

        ActivityBean bean = new ActivityBean();
        Unbinder unbinder = ButterKnife.bind(activity);
        bean.setUnbinder(unbinder);
        activity.getIntent().putExtra("ActivityBean", bean);

        if (activity instanceof IActivity) {
            if (((IActivity) activity).useRxBus()) {
                RxBus.get().register(activity);
            }
        }
    }

    @Override
    public void onActivityStarted(Activity activity) {
        Logger.e(activity + " onActivityStarted");

        if (foregroundActivityCount == 0 || !isForegroundNow) {
            willSwitchToForeground = true;
        }

        if (isChangingConfigActivity) {
            isChangingConfigActivity = false;
            return;
        }

        foregroundActivityCount += 1;

        Logger.e("Bining onActivityStarted foregroundActivityCount：" + foregroundActivityCount + "  " + activity);
    }

    @Override
    public void onActivityResumed(Activity activity) {
        Logger.e(activity + " onActivityResumed");

        addAppUseReduceTimeIfNeeded(activity);

        if (willSwitchToForeground && isInteractive(activity)) {
            isForegroundNow = true;
            Logger.e("switch to foreground");
        }

        if (isForegroundNow) {
            willSwitchToForeground = false;
        }
    }

    @Override
    public void onActivityPaused(Activity activity) {
        Logger.e(activity + " onActivityPaused");

        lastPausedActivityName = getActivityName(activity);
        lastPausedActivityHashCode = activity.hashCode();
        lastPausedTime = System.currentTimeMillis();
    }

    @Override
    public void onActivityStopped(Activity activity) {
        Logger.e(activity + " onActivityStopped");

        addAppUseReduceTimeIfNeeded(activity);

        if (activity.isChangingConfigurations()) {
            isChangingConfigActivity = true;
            return;
        }

        foregroundActivityCount -= 1;

        if (foregroundActivityCount == 0) {
            isForegroundNow = false;
            Logger.e("switch to background");
        }

        Logger.e("Bining onActivityStopped foregroundActivityCount：" + foregroundActivityCount + "  " + activity);
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        Logger.e(activity + " onActivitySaveInstanceState");
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        Logger.e(activity + " onActivityDestroyed");

        ActivityBean bean = (ActivityBean) activity.getIntent().getSerializableExtra("ActivityBean");
        //取消注册ButterKnife
        Unbinder unbinder = bean.getUnbinder();
        if (unbinder != null || unbinder != Unbinder.EMPTY) {
            unbinder.unbind();
        }

        if (activity instanceof IActivity) {
            if (((IActivity) activity).useRxBus()) {
                RxBus.get().unregister(activity);
            }
        }

        Logger.e("Bining onActivityDestroyed foregroundActivityCount：" + foregroundActivityCount + "  " + activity);
        if (appUseReduceTime > 0) {
            Logger.e("Bining 应用暂停时间：" + appUseReduceTime + "  " + activity);
        }
    }

    private void addAppUseReduceTimeIfNeeded(Activity activity) {
        if (getActivityName(activity).equals(lastPausedActivityName) && activity.hashCode() == lastPausedActivityHashCode) {
            long now = System.currentTimeMillis();
            if (now - lastPausedTime > 1000) {
                appUseReduceTime += now - lastPausedTime;
            }
        }

        lastPausedActivityHashCode = -1;
        lastPausedActivityName = null;
        lastPausedTime = 0;
    }

    private boolean isInteractive(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            return pm.isInteractive();
        } else {
            return pm.isScreenOn();
        }
    }

    private String getActivityName(final Activity activity) {
        return activity.getClass().getCanonicalName();
    }

}
